<?php
/*
 module:		发布管理
 create_time:	2022-03-09 16:30:59
 author:	陕西格创
 contact:		
*/

namespace app\api\controller;

use app\api\model\ZhAuthentication as ZhAuthenticationModel;
use app\api\model\ZhAuthParent as ZhAuthParentModel;
use app\backend\model\SysSite as SysSiteModel;
use app\api\model\Member as MemberModel;
use app\api\model\ZhCollection as ZhCollectionModel;
use think\facade\Db;

class ZhAuthParent extends Common
{


    function index()
    {
        $wxapp_id       = $this->request->get('wxapp_id');
        $op= $this->request->get('op','');
        $uid   = 0;
        if($op=="test"){
            $uid=395;
        }else{
            // 获取用户id 用以判断用户是否登录
            $token = $this->request->header('Authorization');

            if ($token) {
                $jwt = Jwt::getInstance();
                $jwt->setIss(config('my.jwt_iss'))->setAud(config('my.jwt_aud'))
                    ->setSecrect(config('my.jwt_secrect'))
                    ->setToken($token);
                $uid  = $jwt->decode()->getClaim('uid');
                $user = MemberModel::where(['uid' => $uid, 'wxapp_id' => $wxapp_id])->find();
                if (!$user) {
                    return $this->ajaxReturn($this->errorCode, '未知用户');
                }
            }
        }

        $auth_parent=ZhAuthParentModel::field("id,other_describe,u_id,gender,min_age,max_age,city")->where(["u_id"=>$uid])->find();
        if(!$auth_parent){
            return $this->ajaxReturn($this->errorCode, '未知家长用户');
        }

        $gender         = intval($auth_parent["gender"]); // 性别
        $min_age=$auth_parent["min_age"];
        $max_age=$auth_parent["max_age"];
        $city           =$auth_parent["city"];
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
        $limit = $this->request->get('limit', 20, 'intval');
        $page  = $this->request->get('page', 1, 'intval');
        $is_top= $this->request->get('is_top', 0, 'intval');
        $wheres="a.wxapp_id = {$wxapp_id} and a.gender !={$gender}";
        if($this->request->has("is_top")){
            $wheres.=" and a.is_top='{$is_top}'";
        }
        if ($city) {
            $wheres.=" and a.city='{$city}'";
        }
        if ($min_age) {
            $wheres.=" and a.age >='{$min_age}'";
        }
        if ($max_age) {
            $wheres.=" and a.age <='{$max_age}'";
        }

        $query = ZhAuthenticationModel::alias('a')->where($wheres);
         $res = $query->field("a.occupation,a.authentication_id,a.is_top ,a.purchase_status,a.income,a.vehicle_status,a.marital_status, a.work,a.status,a.age,a.gender,a.education,a.authentication_id,a.head_portrait,a.real_name,a.date_birth,a.city,a.height,a.weight,a.u_id,a.photos,a.lova_declaration")->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
        foreach ($query as &$v) {
            $userInfo          = MemberModel::where(['wxapp_id' => $wxapp_id, 'uid' => $v['u_id']])->find();
            $isVip             = $userInfo['is_vip'];
            $is_auth           = $userInfo['is_auth'];
            $tags              = empty($userInfo['tags']) ? [] : explode(',', $userInfo['tags']);
            $certify_tags      = empty($userInfo['certify_tags']) ? [] : explode(',', $userInfo['certify_tags']);
            $v['is_vip']       = $isVip;
            $v['tags']         = $tags;
            $v['is_auth']      = $is_auth;
            $v['certify_tags'] = $certify_tags;
            $ZhCollectionData  = ZhCollectionModel::where(['u_id' => $uid, 'wxapp_id' => $wxapp_id, 'marriage_seeking_id' => $v['authentication_id']])->find();
            if ($ZhCollectionData) {
                $v['is_collection'] = $ZhCollectionData['status'];
            } else {
                $v['is_collection'] = 0;
            }
            if ($v['photos']) {
                $v['photos'] = explode(',', $v['photos']);
            } else {
                $v['photos'] = $this->request->domain() . '/static/web/img/zhanweitu.png';
                $v['photos'] = explode(',', $v['photos']);
            }

        }
        $res["auth_parent"]=$auth_parent;
        $res["authentication"]=$query;
        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }


    /**
     * @api             {get} /ZhAuthentication/view 02、查看详情
     * @apiGroup        ZhAuthentication
     * @apiVersion      1.0.0
     * @apiDescription  查看详情
     * @apiParam (输入参数：) {string}            authentication_id 主键ID
     * @apiHeader {String} Authorization 用户授权token
     * @apiHeaderExample {json} Header-示例:
     * "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
     * @apiParam (失败返回参数：) {object}        array 返回结果集
     * @apiParam (失败返回参数：) {string}        array.status 返回错误码 201
     * @apiParam (失败返回参数：) {string}        array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}        array 返回结果集
     * @apiParam (成功返回参数：) {string}        array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}        array.data 返回数据详情
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":""}
     * @apiErrorExample {json} 02 失败示例
     * {"status":"201","msg":"没有数据"}
     */
    function view()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        $id=$this->request->get('id');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
     /*   // 获取用户id 用以判断用户是否登录
        $token = $this->request->header('Authorization');
        $uid   = 0;
        if ($token) {
            $jwt = Jwt::getInstance();
            $jwt->setIss(config('my.jwt_iss'))->setAud(config('my.jwt_aud'))
                ->setSecrect(config('my.jwt_secrect'))
                ->setToken($token);
            $uid  = $jwt->decode()->getClaim('uid');
            $user = MemberModel::where(['uid' => $uid, 'wxapp_id' => $wxapp_id])->find();
            if (!$user) {
                return $this->ajaxReturn($this->errorCode, '未知用户');
            }
        }*/

        $data['id'] = $id;
        $res                       = \app\api\model\ZhAuthParent::where($data)->find();
        return $this->ajaxReturn($this->successCode, '返回成功', $res ?: '');
    }

    function add()
    {
        $wxapp_id = $this->request->post('wxapp_id');
        $id     = $this->request->post('id');
        $type     = $this->request->post('type');
        $userType = $this->request->post('user_type', '', 'serach_in');
        $zhPhone  = $this->request->post('zhphone', '', 'serach_in');
        $auth = ZhAuthParentModel::where(['id' => $id])->find();
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $postField            = 'o_jg,work,self_built,age,notes,matchmaker_id,u_id,wxapp_id,authentication_id,head_portrait,real_name,gender,date_birth,city,height,weight,photos,real_name,user_type,matchmaker_id';
        $postField = $postField.",simple_name,is_party_member,mbti,constellation,tags,o_age,o_height,o_city,o_weight,o_education,o_marital_status";
        $postField = $postField.",animal,appearance,belief,parental_status,sibling,zodiac_clash,commitment,contacts,is_smoking,is_drink,vehicle_status,lova_declaration";
        $postField = $postField.",education,nation,occupation,family_status,o_income,o_nation,income,o_remarks,o_is_drink,o_is_smoking,o_vehicle_status,o_purchase_status,purchase_status";
        $postField = $postField.",min_age,max_age,region,street,other_describe";
        $data                 = $this->request->only(explode(',', $postField), 'post', null);
        $data['head_portrait'] = $this->request->post('image');
        $data['marital_status'] = $this->request->post('marital_status') == '未婚' ? 0 : ($this->request->post('marital_status') == '离异' ? 1 : 2);
        $data['have_children']  = $this->request->post('have_children') == '无' ? 0 : 1;
        $data['contact_type']   = $this->request->post('contact_type') == 1 ? '微信' : ($this->request->post('contact_type') == 2 ? 'QQ' : '电话');
        $data['lova_declaration'] = $this->request->post('lova_declaration');
        $data['status']            = 0;
        $data['release_type'] = 0;
        //添加记录红娘id
        $data['videos']               = json_encode($this->request->post('videos'));
        //&& $userType != 2
        if ($auth ) {
            $res = ZhAuthParentModel::where('id', $id)->update($data);
        } else {
            $MemberData = MemberModel::where(['wxapp_id' => $wxapp_id, 'phone' => $zhPhone])->find();
            if ($MemberData) {
                return $this->ajaxReturn($this->errorCode, '该手机号已绑定用户，请重新发布');
            } else {
                $memberId = MemberModel::insertGetId([
                    'wxapp_id'      => $wxapp_id,
                    'phone'         => $zhPhone,
                    'real_name'     => $data['real_name'],
                    'create_time'   => time(),
                    'matchmaker_id' => 0
                ]);
                if ($memberId) {
                    $uId = $memberId;
                } else {
                    return $this->ajaxReturn($this->errorCode, '发布失败，请稍后重试');
                }
                $data['wxapp_id']   = $wxapp_id;
                $data['u_id']       = $memberId;
                $data['gender']=0;
                $data['createtime'] = time();
                $parentid_id = \app\api\model\ZhAuthParent::create($data);
            }
        }
        return $this->ajaxReturn($this->successCode, '操作成功', $res);
    }
    function edit(){
        $id=$this->request->post('id');
        if($id<=0){
            return $this->ajaxReturn($this->errorCode, 'id不可小于0');
        }
        $data=[];
        if($this->request->has('gender')){
            $data['gender']     = $this->request->post('gender');
        }
        if($this->request->has('min_age')){
            $data['min_age']     = $this->request->post('min_age');
        }
        if($this->request->has('max_age')){
            $data['max_age']     = $this->request->post('max_age');
        }
        if($this->request->has('city')){
            $data['city']     = $this->request->post('city');
        }
        if($this->request->has('region'))  {
            $data['region']     = $this->request->post('region');
        }
        if($this->request->has('street')){
            $data['street']     = $this->request->post('street');
        }
        if($this->request->has('other_describe')){
            $data['other_describe']     = $this->request->post('other_describe');
        }
        ZhAuthParentModel::where(['id' => $id])
            ->update($data);
        return $this->ajaxReturn($this->successCode, '操作成功');
    }


    //删除
    function delete(){
        $id  = intval($this->request->post('id'));
        if($id<=0){
            return $this->ajaxReturn($this->errorCode, '请传递正确的id');
        }
        //直接删除
        $res = ZhAuthParent::where('id',$id)->delete();

        if($res){
            return $this->ajaxReturn($this->successCode, '删除成功');
        }else{
            return $this->ajaxReturn($this->errorCode, '删除失败');
        }

    }


}

